package org.jeecg.modules.consumptionElectricity.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DySmsEnum;
import org.jeecg.common.util.DySmsHelper;
import org.jeecg.modules.consumptionElectricity.entity.AnalysisDTO;
import org.jeecg.modules.consumptionElectricity.entity.ConsumptionElectricity;
import org.jeecg.modules.consumptionElectricity.entity.ElectricitySelectDTO;
import org.jeecg.modules.consumptionElectricity.entity.TrackingDTO;
import org.jeecg.modules.consumptionElectricity.service.IConsumptionElectricityService;
import org.jeecg.modules.errorLog.entity.Error;
import org.jeecg.modules.errorLog.service.IErrorService;
import org.jeecg.modules.output.entity.Output;
import org.jeecg.modules.output.service.IOutputService;
import org.jeecg.modules.product.entity.Product;
import org.jeecg.modules.product.service.IProductService;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @Description: 电能能耗
 * @Author: jeecg-boot
 * @Date:   2023-06-20
 * @Version: V1.0
 */
@Api(tags="电能能耗")
@RestController
@RequestMapping("/consumptionElectricity/consumptionElectricity")
@Slf4j
public class ConsumptionElectricityController extends JeecgController<ConsumptionElectricity, IConsumptionElectricityService> {
	@Autowired
	private IConsumptionElectricityService consumptionElectricityService;
	@Autowired
	private IOutputService outputService;
	@Autowired
	private IProductService productService;
	@Autowired
	private ISysDepartService sysDepartService;
	@Autowired
	private IErrorService errorService;

	/**
	 * 分页列表查询
	 *
	 * @param consumptionElectricity
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "电能能耗-分页列表查询")
	@ApiOperation(value="电能能耗-分页列表查询", notes="电能能耗-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ConsumptionElectricity consumptionElectricity,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ConsumptionElectricity> queryWrapper = QueryGenerator.initQueryWrapper(consumptionElectricity, req.getParameterMap());
		Page<ConsumptionElectricity> page = new Page<ConsumptionElectricity>(pageNo, pageSize);
		IPage<ConsumptionElectricity> pageList = consumptionElectricityService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	@GetMapping("/getAll")
	public Result<?> getAll(){
		List<ConsumptionElectricity> list = consumptionElectricityService.list();
		return Result.OK(list);
	}

	@GetMapping("/getByPoint")
	public Result<?> getByPoint(@RequestParam String point){
		LambdaQueryWrapper<ConsumptionElectricity> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(ConsumptionElectricity::getPoint, point);
		List<ConsumptionElectricity> list = consumptionElectricityService.list(wrapper);
		return Result.OK(list);
	}

	@AutoLog(value = "电能能耗-根据部门和时间范围查询")
	@PostMapping("/select")
	public Result<?> select(@RequestBody ElectricitySelectDTO selectDTO){
		List<ConsumptionElectricity> list = consumptionElectricityService.selectByTime(selectDTO);
		return Result.OK(list);
	}

	@GetMapping("/getAllGroupByDept")
	public Result<?> getAllGroupByDept(){
		List<Map<String, Object>> list = consumptionElectricityService.getAllGroupByDept();
		return Result.OK(list);
	}

	@PostMapping("/getUnitConsumption")
	public Result<?> getUnitConsumption(@RequestBody ElectricitySelectDTO selectDTO){
		List<ConsumptionElectricity> consumptionElectricity = consumptionElectricityService.selectByTime(selectDTO);
		List<Output> outputs = outputService.selectByTime(selectDTO);
		Calendar calendar = Calendar.getInstance();
		List<Map<String, Object>> list = new LinkedList<>();
		for (Output o : outputs){
			calendar.setTime(o.getTime());
			String year = String.valueOf(calendar.get(Calendar.YEAR));
			String month = String.valueOf(calendar.get(Calendar.MONTH)+1);
			String day = String.valueOf(calendar.get(Calendar.DATE));
			for (ConsumptionElectricity ce : consumptionElectricity){
				if ("date".equals(selectDTO.getDatePickerType())){
					if (year.equals(ce.getYear()) && month.equals(ce.getMonth()) && day.equals(ce.getDay())){
						Map<String, Object> map = new HashMap<>();
						BigDecimal output = new BigDecimal(o.getOutput());
						BigDecimal consumption = ce.getConsumption();
						BigDecimal unitConsumption = consumption.divide(output,2, RoundingMode.HALF_UP);
						map.put("unitConsumption", unitConsumption);
						map.put("year", year);
						map.put("month", month);
						map.put("day", day);
						list.add(map);
					}
				} else {
					if (year.equals(ce.getYear()) && month.equals(ce.getMonth())){
						Map<String, Object> map = new HashMap<>();
						BigDecimal output = new BigDecimal(o.getOutput());
						BigDecimal consumption = ce.getConsumption();
						BigDecimal unitConsumption = consumption.divide(output,2, RoundingMode.HALF_UP);
						map.put("unitConsumption", unitConsumption);
						map.put("year", year);
						map.put("month", month);
						list.add(map);
					}
				}
			}
		}
		return Result.OK(list);
	}

	@PostMapping("/getUnitCarbonEmission")
	public Result<?> getUnitCarbonEmission(@RequestBody ElectricitySelectDTO selectDTO){
		List<ConsumptionElectricity> consumptionElectricity = consumptionElectricityService.selectCarbonEmission(selectDTO);
		List<Output> outputs = outputService.selectCarbonEmission(selectDTO);
		List<Product> products = productService.list();
		List<Map<String, Object>> list = new LinkedList<>();
		for (Product p : products){
			Map<String, Object> map = new HashMap<>();
			String product = p.getName();
			BigDecimal unitCarbonEmission = getBigDecimal(consumptionElectricity, product, outputs);
			map.put("product", product);
			map.put("unitCarbonEmission", unitCarbonEmission);
			list.add(map);
		}
		log.info("list: {}", list);
		return Result.OK(list);
	}

	@NotNull
	private static BigDecimal getBigDecimal(List<ConsumptionElectricity> consumptionElectricity, String product, List<Output> outputs) {
		BigDecimal carbonEmission = BigDecimal.ZERO;
		BigDecimal output = BigDecimal.ZERO;
		BigDecimal unitCarbonEmission = BigDecimal.ZERO;
		for (ConsumptionElectricity ce : consumptionElectricity){
			if (product.equals(ce.getProduct())){
				BigDecimal carbonEmission1 = ce.getCarbonEmission();
				carbonEmission = carbonEmission.add(carbonEmission1);
			}
		}
		for (Output op : outputs){
			if (product.equals(op.getProduct())){
				output = output.add(new BigDecimal(op.getOutput()));
			}
		}
		if (!(output.equals(BigDecimal.ZERO))){
			unitCarbonEmission = carbonEmission.divide(output, 4, RoundingMode.HALF_UP);
		}
		return unitCarbonEmission;
	}

	@PostMapping("/getProductConsumption")
	public Result<?> getProductConsumption(@RequestBody ElectricitySelectDTO selectDTO){
		List<ConsumptionElectricity> list = consumptionElectricityService.selectProductConsumption(selectDTO);
		return Result.OK(list);
	}

	@PostMapping("/getTracking")
	public Result<?> getTracking(@RequestBody TrackingDTO trackingDTO){
		List<List<ConsumptionElectricity>> tracking = consumptionElectricityService.getTracking(trackingDTO);
		return Result.OK(tracking);
	}

	@GetMapping("/loadElectricityTotal")
	public Result<?> loadElectricityTotal(){
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		QueryWrapper<ConsumptionElectricity> wrapper = new QueryWrapper<>();
		wrapper.select("sum(consumption) as consumption", "year", "month").eq("year", year)
				.groupBy("month", "year").orderByAsc("year*1", "month*1");
		List<ConsumptionElectricity> list = consumptionElectricityService.list(wrapper);
		return Result.OK(list);
	}

	@GetMapping("/getCard")
	public Result<?> getCard(){
		Map<String, Object> map = new HashMap<>();
		Map<String, BigDecimal> avgMonth = new HashMap<>();
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH)+1;
		QueryWrapper<ConsumptionElectricity> wrapper = new QueryWrapper<>();
		wrapper.select("sum(consumption) as consumption", "ROUND(sum(cost),2) as cost", "ROUND(sum(carbon_emission),2) as carbonEmission",
						"ROUND(sum(coal_emission),2) as coalEmission", "year", "month")
				.eq("year", year).eq("month", month).groupBy("month", "year");
		ConsumptionElectricity thisMonth = consumptionElectricityService.getOne(wrapper);
		wrapper.clear();
		wrapper.select("sum(consumption) as consumption", "ROUND(sum(cost),2) as cost", "ROUND(sum(carbon_emission),2) as carbonEmission",
						"ROUND(sum(coal_emission),2) as coalEmission", "year").eq("year", year)
				.groupBy("year").orderByAsc("year*1");
		ConsumptionElectricity thisYear = consumptionElectricityService.getOne(wrapper);
		BigDecimal bigMonth = new BigDecimal(month);
		BigDecimal bigDecimal1 = new BigDecimal("0");
		if (!thisYear.getConsumption().equals(BigDecimal.ZERO)){
			bigDecimal1 = thisYear.getConsumption().divide(bigMonth, RoundingMode.HALF_UP);
		}
		avgMonth.put("consumption", bigDecimal1);
		bigDecimal1 = BigDecimal.ZERO;
		if (!thisYear.getCost().equals(BigDecimal.ZERO)){
			bigDecimal1 = thisYear.getCost().divide(bigMonth, RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP);
		}
		avgMonth.put("cost", bigDecimal1);
		bigDecimal1 = BigDecimal.ZERO;
		if (!thisYear.getCarbonEmission().equals(BigDecimal.ZERO)){
			bigDecimal1 = thisYear.getCarbonEmission().divide(bigMonth, RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP);
		}
		avgMonth.put("carbonEmission", bigDecimal1);
		bigDecimal1 = BigDecimal.ZERO;
		if (!thisYear.getCoalEmission().equals(BigDecimal.ZERO)){
			bigDecimal1 = thisYear.getCoalEmission().divide(bigMonth, RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP);
		}
		avgMonth.put("coalEmission", bigDecimal1);
		map.put("thisMonth", thisMonth);
		map.put("avgMonth", avgMonth);
		map.put("thisYear", thisYear);
		return Result.OK(map);
	}

	@GetMapping("/getIndexChart")
	public Result<?> getIndexChart(){
		QueryWrapper<ConsumptionElectricity> wrapper = new QueryWrapper<>();
		wrapper.select("dept", "sum(consumption) as consumption", "ROUND(sum(cost),2) as cost", "ROUND(sum(carbon_emission),2) as carbonEmission",
						"ROUND(sum(coal_emission),2) as coalEmission")
				.groupBy("dept").orderByDesc("consumption");
		List<ConsumptionElectricity> list = consumptionElectricityService.list(wrapper);
		return Result.OK(list);
	}

	@GetMapping("/getScreenHeaderTime")
	public Result<?> getScreenHeaderTime(){
		long l = System.currentTimeMillis();
		return Result.OK(l);
	}

	@GetMapping("/getScreenLeftTop")
	public Result<?> getScreenLeftTop(){
		List<Map<String, Object>> list = sysDepartService.getScreenLeftTop();
		return Result.OK(list);
	}

	@GetMapping("/getScreenLeftMiddle")
	public Result<?> getScreenLeftMiddle(){
		List<Map<String, Object>> list = sysDepartService.getScreenLeftMiddle();
		return Result.OK(list);
	}

	@GetMapping("/getScreenLeftBottom")
	public Result<?> getScreenLeftBottom(){
		List<Map<String, Object>> list = sysDepartService.getScreenLeftBottom();
		return Result.OK(list);
	}

	@GetMapping("/getScreenRightTop")
	public Result<?> getScreenRightTop(){
		List<Map<String, Object>> list = sysDepartService.getScreenRightTop();
		return Result.OK(list);
	}

	@GetMapping("/getScreenRightMiddle")
	public Result<?> getScreenRightMiddle(){
		List<Map<String, Object>> list = sysDepartService.getScreenRightMiddle();
		return Result.OK(list);
	}

	@PostMapping("/getAnalysis")
	public Result<?> getAnalysis(@RequestBody AnalysisDTO analysisDTO){
		log.info("信息：{}", analysisDTO);
		String leftValue = analysisDTO.getLeftValue();
		String rightValue = analysisDTO.getRightValue();
		String[] leftDateString = analysisDTO.getLeftDate();
		String[] rightDateString = analysisDTO.getRightDate();
		if (leftDateString.length != 2 || rightDateString.length != 2){
			Error error = new Error();
			error.setCause("不合法的字符串长度");
			error.setMessage("检查对比时间完整性");
			errorService.save(error);
			return Result.error("服务器繁忙，请稍后再试。");
		}
		LambdaQueryWrapper<ConsumptionElectricity> wrapper = Wrappers.lambdaQuery();
		wrapper.and(q -> q.eq(ConsumptionElectricity::getPoint, leftValue).or()
						.eq(ConsumptionElectricity::getProductionLine, leftValue).or()
						.eq(ConsumptionElectricity::getProduct, leftValue).or()
						.eq(ConsumptionElectricity::getDept, leftValue))
				.between(ConsumptionElectricity::getDate, leftDateString[0], leftDateString[1]);
		List<ConsumptionElectricity> leftList = consumptionElectricityService.list(wrapper);
		wrapper.clear();
		wrapper.and(q -> q.eq(ConsumptionElectricity::getPoint, rightValue).or()
						.eq(ConsumptionElectricity::getProductionLine, rightValue).or()
						.eq(ConsumptionElectricity::getProduct, rightValue).or()
						.eq(ConsumptionElectricity::getDept, rightValue))
				.between(ConsumptionElectricity::getDate, rightDateString[0], rightDateString[1]);
		List<ConsumptionElectricity> rightList = consumptionElectricityService.list(wrapper);
		List<List<?>> list = new ArrayList<>();
		list.add(leftList);
		list.add(rightList);
		return Result.OK(list);
	}

	@AutoLog(value = "电能能耗-测试数据")
	@ApiOperation(value="电能能耗-测试数据", notes="电能能耗-测试数据")
	@GetMapping(value = "/carbonEmissionAndCost")
	public Result<?> carbonEmissionAndCost() {
		List<ConsumptionElectricity> list = consumptionElectricityService.list();
		list.forEach(consumptionElectricity -> {
					if (consumptionElectricity.getProduct().equals("空压机")) {
						consumptionElectricity.setProductionLine("COMP-4");
						consumptionElectricity.setDevice("空压机-COMP-4");
						consumptionElectricity.setEnergyMeterId("00030098010176");
						consumptionElectricity.setPoint("3期机械室");
					} else if (consumptionElectricity.getProduct().equals("成型机")) {
						consumptionElectricity.setProductionLine("成型机-001");
						consumptionElectricity.setDevice("成型机-001");
						consumptionElectricity.setEnergyMeterId("00033313010149");
						consumptionElectricity.setPoint("3期电气室");
					}
				});
		consumptionElectricityService.updateBatchById(list);
		return Result.OK("添加成功！");
	}

	@AutoLog(value = "电能能耗-短信推送")
	@ApiOperation(value="电能能耗-短信推送", notes="电能能耗-短信推送")
	@GetMapping("/addProduct")
	public Result<?> addProduct() throws ClientException {
		//手机号
		String mobile = "18202591671";
		//消息模版,此处是登录验证模版
		DySmsEnum templateCode = DySmsEnum.REGISTER_TEMPLATE_CODE;
		//模版所需参数
		JSONObject obj = new JSONObject();
		obj.put("code", "4XDP");
		DySmsHelper.sendSms(mobile, obj, templateCode);
		return Result.OK("???");
	}

	/**
	 *   添加
	 *
	 * @param consumptionElectricity
	 * @return
	 */
	@AutoLog(value = "电能能耗-添加")
	@ApiOperation(value="电能能耗-添加", notes="电能能耗-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ConsumptionElectricity consumptionElectricity) {
		consumptionElectricityService.save(consumptionElectricity);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param consumptionElectricity
	 * @return
	 */
	@AutoLog(value = "电能能耗-编辑")
	@ApiOperation(value="电能能耗-编辑", notes="电能能耗-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ConsumptionElectricity consumptionElectricity) {
		consumptionElectricityService.updateById(consumptionElectricity);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "电能能耗-通过id删除")
	@ApiOperation(value="电能能耗-通过id删除", notes="电能能耗-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		consumptionElectricityService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "电能能耗-批量删除")
	@ApiOperation(value="电能能耗-批量删除", notes="电能能耗-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.consumptionElectricityService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "电能能耗-通过id查询")
	@ApiOperation(value="电能能耗-通过id查询", notes="电能能耗-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		ConsumptionElectricity consumptionElectricity = consumptionElectricityService.getById(id);
		if(consumptionElectricity==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(consumptionElectricity);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param consumptionElectricity
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ConsumptionElectricity consumptionElectricity) {
        return super.exportXls(request, consumptionElectricity, ConsumptionElectricity.class, "电能能耗");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ConsumptionElectricity.class);
    }

}
